package com.spark.sniffer.plugin.plugins.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import com.spark.sniffer.logging.api.Logger;
import com.spark.sniffer.logging.api.LoggerFactory;
import com.spark.sniffer.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import com.spark.sniffer.plugin.interceptor.enhance.MethodInterceptResult;
import com.spark.sniffer.tracing.TracingContext;
import com.spark.sniffer.util.ReflectUtil;
import com.spark.sniffer.util.ReflectUtil.WrapperMethod;

public class ClientHttpRequestInterceptor implements InstanceMethodsAroundInterceptor {
    private static final Logger log = LoggerFactory.getLogger(ClientHttpRequestInterceptor.class);

    @Override
    public void beforeMethod(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        MethodInterceptResult result) throws Throwable {

        // 开始设置header
        // 设置透传数据
        Map<String, String> passThroughMap = TracingContext.getContext().getPassThroughMap();
        if (passThroughMap != null && !passThroughMap.isEmpty()) {
            Object httpHeadersInstance = ReflectUtil.getMethod(instance, "getHeaders").invoke();// org.springframework.http.HttpHeaders

            WrapperMethod setAllMethod = ReflectUtil.getMethod(httpHeadersInstance, "setAll", Map.class);// HttpHeaders.setAll(Map<String, String>)
            setAllMethod.invoke(passThroughMap);

            if (log.isDebugEnable()) {
                passThroughMap.entrySet()
                    .forEach(x -> log.debug("pass through RestTemplate header, {}={}", x.getKey(), x.getValue()));
            }
        }
    }

    @Override
    public Object afterMethod(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        Object ret) throws Throwable {
        return ret;
    }

    @Override
    public void handleMethodException(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        Throwable t) {}

}
